package com.huike.pmps.config.interceptor;

import com.huike.pmps.dao.MemberDao;
import com.huike.pmps.model.entity.Member;
import com.huike.pmps.model.vo.security.MenuVo;
import com.huike.pmps.service.PermissionService;
import com.huike.pmps.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;


/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */

/**
 * 测试通过
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {


    @Autowired
    private MemberDao memberDao;

    @Autowired
    private PermissionService permissionService;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
            String token = TokenUtil.getToken(request);
            //统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
            Member member = (Member) request.getSession().getAttribute(token);
            if (member == null) {
                Principal principal = request.getUserPrincipal();
                if (principal != null) {
                    List<Integer> rolesIds = new ArrayList<>();
                    String memberName = principal.getName();
                    member = memberDao.findByMemberName(memberName);
                    member.getRoles().forEach(r -> {
                        rolesIds.add(r.getId());
                        r.setPermissions(null);
                    });
                    member.setRolesIds(rolesIds);
                    List<MenuVo> menuVos = permissionService.selectPermissionByMemberId(member.getId());
                    //设置用户菜单
                    member.setMenus(menuVos);
                    if (member == null) {
                        throw new UsernameNotFoundException(memberName);
                    }
                    request.getSession().setAttribute(token, member);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //System.out.println("执行了TestInterceptor的afterCompletion方法");
    }


}
